import React from "react";
import View from "../base/View";
import defaultData from "./data";
import { Map } from 'react-amap';
import classNames from 'classnames';
import './index.less';

export default class MapView extends View {
  constructor(props) {
    super(props);

    this.state = {
      isFail: false
    };

    this.map = null;
    this.marker = null;
    this.placeSearch = null;
    this.geocoder = null;
    this.mapCenter = { longitude: 120, latitude: 30 };
    this.mapEvents = {
      created: (mapInstance) => {
        this.map = mapInstance;

        AMap.plugin(['AMap.PlaceSearch', 'AMap.Geocoder'], () => {
          this.placeSearch = new AMap.PlaceSearch();
          this.marker = new AMap.Marker();

          this.getLocation(this.props.data.location);
        });
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.data.location !== this.props.data.location) {
      this.getLocation(nextProps.data.location)
    }
  }

  getLocation = address => {//定位到设置的位置
    this.setState({
      isFail: false
    });
    this.placeSearch.search(address, (status, result) => {
      if(status === 'complete' && result.info === 'OK') {
        this.map.remove(this.marker);
        this.map.add(this.marker);
        this.marker.setPosition(result.poiList.pois[0].location);
        this.map.setFitView(this.marker);
      } else {
        this.setState({
          isFail: true
        });
      }
    });
  }

  renderContent() {
    const { isFail } = this.state;

    return (
      <div className='wea-edc-map-conatiner'>
        <Map 
          zoom={5}
          jogEnable={false}
          animateEnable={false} 
          center={this.mapCenter} 
          events={this.mapEvents} 
        />
        <div className={classNames("fail-map", { hide: !isFail })}></div>
      </div>
    );
  }
}

MapView.defaultProps = {
  data: defaultData,
  value: ''
};